<template>
  <div class="container">
    <Breadcrumb :items="['系统管理', '角色管理']"/>
    <a-card class="general-card" title="角色管理">
      <a-divider style="margin-top: 0"/>
      <a-table
          row-key="id"
          :loading="loading"
          :columns="columns"
          :data="renderData"
          :bordered="false"
          :size="size"
          :pagination="pagination"
          page-position="bl"
          @page-change="pageChange"
          @page-size-change="pageSizeChange"
      >
        <template #operations="{ record }">
          <a-button v-permission="['admin']" type="text" size="small" @click="updateItem(record.roleId)">
            <template #icon>
              <icon-edit/>
            </template>
            编辑
          </a-button>
        </template>
      </a-table>
    </a-card>

    <!--  表单  -->
    <a-modal ref="modalRef" v-model:visible="formModelSetting.visible" :ok-loading="formModelSetting.onLoading"
             :mask-closable="false" :title="formModelSetting.title" title-align="start"
             :ok-text="formModelSetting.okText" cancel-text="取消" @cancel="modelCancelBut"
             @before-ok="modelBeforeOkBut" @ok="modelOkBut">
      <a-form ref="formRef" :model="formData">
        <a-form-item field="roleName" label="角色名称">
          <a-input v-model="formData.roleName" disabled show-word-limit/>
        </a-form-item>
        <a-form-item field="roleDesc" label="描述">
          <a-textarea v-model="formData.roleDesc" placeholder="请输入角色描述" max-length="200" show-word-limit
                      auto-size/>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import {computed, reactive, ref} from 'vue';
import useLoading from '@/hooks/loading';
import type {TableColumnData} from '@arco-design/web-vue/es/table/interface';
import {Message} from "@arco-design/web-vue";
import {Pagination} from '@/types/global';
import {edit, EditRoleParams, getRoleById, roleList, RoleParams} from '@/api/system/role';

type SizeProps = 'mini' | 'small' | 'medium' | 'large';

const size = ref<SizeProps>('medium');
const {loading, setLoading} = useLoading(true);

// 对话框是否展示
const formModelSetting = reactive({
  visible: false,
  onLoading: false,
  title: "修改角色",
  okText: "修改",
  cancelText: "",
});

// 表格列
const columns = computed<TableColumnData[]>(() => [
  {
    title: '角色编号',
    dataIndex: 'roleId',
    align: 'center',
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
    align: 'center',
  },
  {
    title: '权限标识',
    dataIndex: 'roleKey',
    align: 'center',
  },
  {
    title: '排序',
    dataIndex: 'roleSort',
    align: 'center',
  },
  {
    title: '说明',
    dataIndex: 'roleDesc',
    align: 'center',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    align: 'center',
  },
]);
const renderData = ref<RoleParams[]>([]);

// 表格数据模型
const tableFormModel = () => {
  return {
    roleId: '',
    roleName: '',
    roleKey: '',
    roleSort: '',
    roleDesc: '',
  };
};
const formModel = ref(tableFormModel());

// 分页
const basePagination: Pagination = {
  pageNumber: 1,
  pageSize: 10,
};
const pagination = reactive({
  ...basePagination,
});
const pageChange = async (pageNumber: number) => {
  pagination.pageNumber = pageNumber;
  await getRoleList({
    ...pagination,
    ...formModel.value,
  } as unknown as RoleParams);
}
const pageSizeChange = async (pageSize: number) => {
  pagination.pageSize = pageSize;
  await getRoleList({
    ...pagination,
    ...formModel.value,
  } as unknown as RoleParams);
}

// 查询角色列表
const getRoleList = async (
    params: RoleParams = {
      roleId: 0,
      roleName: "",
      roleKey: "",
      roleSort: "",
      roleDesc: ""
    }
) => {
  setLoading(true);
  try {
    const {data} = await roleList(params);
    renderData.value = data.rows;
    pagination.total = data.total;
  } catch (err) {
    console.log(err);
  } finally {
    setLoading(false);
  }
};
getRoleList();

// 表单模型
const formData = reactive({
  roleId: 0,
  roleName: '',
  roleDesc: '',
});
// 重置表单模型
const resetFormData = () => {
  formData.roleId = 0;
  formData.roleName = '';
  formData.roleDesc = '';
}
const modalRef = ref();
const formRef = ref();

// 编辑按钮
const updateItem = async (roleId: number) => {
  // 查询
  const {code, msg, data}: any = await getRoleById(roleId);
  if (code === 200 && data) {
    // 赋值
    formData.roleId = data.roleId;
    formData.roleName = data.roleName;
    formData.roleDesc = data.roleDesc;
    // 打开弹窗
    formModelSetting.visible = true;
  } else {
    Message.warning({
      content: msg,
      duration: 2 * 1000,
    });
  }
};

// 取消按钮
const modelCancelBut = () => {
  // 关闭弹窗
  formModelSetting.visible = false;
  formModelSetting.onLoading = false;
  // 重置表单
  resetFormData();
};

// 表单创建之前
const modelBeforeOkBut = async () => {
  let flag = true;
  // 提交表单
  await formRef.value.validate().then(async (res: any) => {
    if (res !== undefined) {
      flag = false;
      // 弹窗不关闭
      formModelSetting.visible = true;
      formModelSetting.onLoading = false;
    }
  });
  return flag;
};

// 表单确定按钮
const modelOkBut = async () => {
  formData.roleName = '';
  const params: EditRoleParams = formData;
  // 调用修改接口
  const {code}: any = await edit(params);
  if (code === 200) {
    Message.success({
      content: '修改成功',
      duration: 2 * 1000,
    });
    // 弹窗关闭
    formModelSetting.visible = false;
    formModelSetting.onLoading = false;
    await getRoleList();
  } else {
    Message.error({
      content: '修改失败',
      duration: 2 * 1000,
    });
    // 弹窗不关闭
    formModelSetting.visible = true;
    formModelSetting.onLoading = false;
  }
}

</script>

<style lang="less" scoped>
.container {
  padding: 0 20px 20px 20px;
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
</style>
